const mqtt = require('mqtt')

const weithTopic = "weight/data"
const rfidTopic = "rfid/data"

let client
const connect = function(broker, onMessage) {
    console.log('message init')
    client = mqtt.connect(broker)

    client.on('connect', () => {
        console.log("message connect")
        client.subscribe(weithTopic)
        client.subscribe(rfidTopic)
        console.log('subscribe')
    })

    client.on('message', (topic, msg) => {
        console.log('message recieve')
        console.log("topic:" + topic);
        console.log("message:" + msg);
        if (onMessage) {
            onMessage(topic, msg.toString())
        }
    })
}

exports.Connect = connect
